//
//  EPBottomPopView.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-1-22.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EPBottomPopView.h"
#import "UIView+Addtions.h"
#import "EpointConsts.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>
#import <MediaPlayer/MediaPlayer.h>

#import "EpointMailSendViewController.h"

#define PopViewHeight 216
#define UpMarginValue 20
#define DownMarginValue 10
#define ItemBtnSideValue 59

typedef enum {
    FILE_TYPE,
    PHOTO_TYPE,
    VIDEO_TYPE
} AttachType;

@interface EPBottomPopView () <UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate> {
    BOOL isMoving;

    NSURL *sourceURL;
    NSString *resultPath;
    NSString *resultQuality;
}

@property (nonatomic, strong) UIScrollView *contentView;
@property (nonatomic, strong) UIPageControl *pageCtrl;
@property (nonatomic, strong) UITableView *attachTable;
@property (nonatomic, strong) NSMutableArray *attachArray;

@end

@implementation EPBottomPopView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id)init {
    self = [super initWithFrame:CGRectMake(0, ScreenHeight-SystemTakeHeight, ScreenWidth, PopViewHeight)];
    self.backgroundColor = COLOR(231, 234, 239);
    if (self) {
        [self addSubViews];
    }
    return self;
}

- (void)addSubViews {
    
    self.contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, PopViewHeight)];
    _contentView.contentSize = CGSizeMake(ScreenWidth*2, PopViewHeight);
    _contentView.pagingEnabled = YES;
    _contentView.showsHorizontalScrollIndicator = NO;
    _contentView.bounces = NO;
    _contentView.tag = 10001;
    _contentView.delegate = self;
    [self addSubview:_contentView];
    
    UIImageView *separatorLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth*2, 1)];
    separatorLine.alpha = 0.5;
    separatorLine.backgroundColor = [UIColor grayColor];
    [_contentView addSubview:separatorLine];
    
    self.pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, PopViewHeight-10, ScreenWidth, 10)];
    _pageCtrl.numberOfPages = 2;
    _pageCtrl.pageIndicatorTintColor = COLOR(134, 190, 216);
    _pageCtrl.currentPageIndicatorTintColor = COLOR(1, 126, 246);
    [_pageCtrl addTarget:self action:@selector(pageCtrlPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_pageCtrl];
    
    [self leftPageView];
    [self rightPageView];
    
}

- (void)pageCtrlPressed:(UIPageControl *)pageCtrl {
    NSLog(@"pageCtrl:%d", _pageCtrl.currentPage);
    if (_pageCtrl.currentPage == 0) {
        [_contentView setContentOffset:CGPointMake(0, 0) animated:YES];
    } else {
        [_contentView setContentOffset:CGPointMake(ScreenWidth, 0) animated:YES];
    }
}

#pragma mark - Left view

- (void)leftPageView {
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, PopViewHeight)];
    [_contentView addSubview:leftView];
    
    UIButton *fileBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [fileBtn setBackgroundImage:[UIImage imageNamed:@"file"] forState:UIControlStateNormal];
    fileBtn.frame = CGRectMake(0, 0, ItemBtnSideValue, ItemBtnSideValue);
    [fileBtn addTarget:self action:@selector(fileBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:fileBtn];
    
    UIButton *photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [photoBtn setBackgroundImage:[UIImage imageNamed:@"photo"] forState:UIControlStateNormal];
    photoBtn.frame = CGRectMake(0, 0, ItemBtnSideValue, ItemBtnSideValue);
    [photoBtn addTarget:self action:@selector(photoBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:photoBtn];
    
    UIButton *videoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoBtn setBackgroundImage:[UIImage imageNamed:@"videoBtn"] forState:UIControlStateNormal];
    videoBtn.frame = CGRectMake(0, 0, ItemBtnSideValue, ItemBtnSideValue);
    [videoBtn addTarget:self action:@selector(videoBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:videoBtn];
    
    CGFloat itemPadding = (ScreenWidth - 3*ItemBtnSideValue)/4;
    CGFloat top = (PopViewHeight - ItemBtnSideValue)/2;
    
    fileBtn.top = top;
    fileBtn.left = itemPadding;
    
    photoBtn.top = top;
    photoBtn.left = itemPadding*2 + ItemBtnSideValue;
    
    videoBtn.top = top;
    videoBtn.left = itemPadding*3 + ItemBtnSideValue*2;
}

- (void)fileBtnPressed {
    NSLog(@"fileBtnPressed ...");
    static int fileCount = 0;
    NSDictionary *fileDic = @{@"type": [[NSNumber alloc] initWithInt:FILE_TYPE], @"title": [NSString stringWithFormat:@"file_%d", fileCount]};
    fileCount++;
    [_attachArray addObject:fileDic];
    [_attachTable reloadData];
}

- (void)photoBtnPressed {
    NSLog(@"photoBtnPressed ...");
    
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"标题" delegate:self cancelButtonTitle:@"cancel" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择", nil];
    sheet.tag = 5000;
    [sheet setActionSheetStyle:UIActionSheetStyleBlackOpaque];
    [sheet showInView:[self window]];
    
//    static int photoCount = 0;
//    NSDictionary *photoDic = @{@"type": [[NSNumber alloc] initWithInt:PHOTO_TYPE], @"title": [NSString stringWithFormat:@"photo_%d", photoCount]};
//    photoCount++;
//    [_attachArray addObject:photoDic];
//    [_attachTable reloadData];
}

- (void)addImageFile:(NSString *)videoFile {
    NSString *fileName = [videoFile lastPathComponent];
    NSDictionary *videoDic = @{@"type": [[NSNumber alloc] initWithInt:PHOTO_TYPE],
                               @"title": fileName,
                               @"fileURL":videoFile};
    [_attachArray addObject:videoDic];
    [_attachTable reloadData];
}

- (void)videoBtnPressed {
    NSLog(@"videoBtnPressed ...");
    
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"标题" delegate:self cancelButtonTitle:@"cancel" destructiveButtonTitle:nil otherButtonTitles:@"拍摄视频",@"从相册中选择", nil];
    sheet.tag = 5001;
    [sheet setActionSheetStyle:UIActionSheetStyleBlackOpaque];
    [sheet showInView:[self window]];
    
//    static int videoCount = 0;
//    NSDictionary *videoDic = @{@"type": [[NSNumber alloc] initWithInt:VIDEO_TYPE], @"title": [NSString stringWithFormat:@"video_%d", videoCount]};
//    videoCount++;
//    [_attachArray addObject:videoDic];
//    [_attachTable reloadData];
}

- (void)addVideoFile:(NSString *)videoFile {
    NSString *fileName = [videoFile lastPathComponent];
    NSDictionary *videoDic = @{@"type": [[NSNumber alloc] initWithInt:VIDEO_TYPE],
                               @"title": fileName,
                               @"fileURL":videoFile};
    [_attachArray addObject:videoDic];
    [_attachTable reloadData];
}

#pragma mark - UISheetActionDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 5000) {
        if (buttonIndex == 0) {
            [self openWithCamera];
        } else {
            [self openWithPhoto:NO];
        }
    } else {
        if (buttonIndex == 0) {
            [self openWithVideo];
        } else {
            [self openWithPhoto:YES];
        }
    }
}

#pragma mark - Photo Camera Vide

- (void)openWithCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = sourceType;
    [_parentCtrl presentViewController:picker animated:YES completion:nil];
}

- (void)openWithPhoto:(BOOL)isVideo {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = sourceType;
    if (isVideo) {
        NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        picker.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];
    }
    [_parentCtrl presentViewController:picker animated:YES completion:nil];
}

- (void)openWithVideo {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    picker.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];
    [_parentCtrl presentViewController:picker animated:YES completion:nil];
    picker.videoMaximumDuration = 30.0f;
    picker.delegate = self;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image;
    NSURL *videoURL;
    
    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        if ([[picker.mediaTypes lastObject] isEqualToString:@"public.image"]) {
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
            [self performSelector:@selector(saveImage:) withObject:@[image, info] afterDelay:0.5];
        } else {
            videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
            [self saveVideo:videoURL];
        }
    } else {
        NSLog(@"type:%@", picker.mediaTypes);
        if ([[picker.mediaTypes lastObject] isEqualToString:@"public.image"]) {
            image = [info objectForKey:UIImagePickerControllerEditedImage];
            [self performSelector:@selector(saveImage:) withObject:@[] afterDelay:0.5];
        } else {
            //public.movie
            videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
            [self saveVideo:videoURL];
        }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveVideo:(NSURL *)videoURL {
    NSLog(@"length:%@", [NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
    NSLog(@"size:%@", [NSString stringWithFormat:@"%f kb", [self getFileSize:[[videoURL absoluteString] substringFromIndex:16]]]);
    NSLog(@"%@" ,[[videoURL absoluteString] substringFromIndex:16]);
    
    resultQuality = AVAssetExportPresetMediumQuality;
    [self compressedFileSize:videoURL];
}

- (void)saveImage:(UIImage *)image {
    NSLog(@"SIZE:%@", NSStringFromCGSize(image.size));
//    [self addVideoFil]
}

#pragma mark - vide deal function

- (void)compressedFileSize:(NSURL *)videoURL {

    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    if ([compatiblePresets containsObject:resultQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:resultQuality];
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];
        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        resultPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/video-%@.mp4", [formater stringFromDate:[NSDate date]]];
        NSLog(@"%@", resultPath);
        exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
         {
             switch (exportSession.status) {
                 case AVAssetExportSessionStatusUnknown:
                     NSLog(@"AVAssetExportSessionStatusUnknown");
                     break;
                 case AVAssetExportSessionStatusWaiting:
                     NSLog(@"AVAssetExportSessionStatusWaiting");
                     break;
                 case AVAssetExportSessionStatusExporting:
                     NSLog(@"AVAssetExportSessionStatusExporting");
                     break;
                 case AVAssetExportSessionStatusCompleted: {
                     NSLog(@"AVAssetExportSessionStatusCompleted");
                     NSString *videoFile = [[exportSession.outputURL absoluteString] substringFromIndex:16];
                     NSLog(@"Completed:%@", videoFile);
                     [self addVideoFile:videoFile];
                 }
                     break;
                 case AVAssetExportSessionStatusFailed:
                     NSLog(@"AVAssetExportSessionStatusFailed");
                     break;
             }
         }];
    }
}

- (CGFloat) getFileSize:(NSString *)path {
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size;
    }
    return filesize;
}

- (CGFloat)getVideoLength:(NSURL *)URL {
    NSDictionary *opts =
    [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:URL options:opts];
    float second = 0;
    second = urlAsset.duration.value/urlAsset.duration.timescale;
    return second;
}

#pragma mark - Right view

- (void)rightPageView {
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth, 1, ScreenWidth, PopViewHeight-1)];
    [_contentView addSubview:rightView];
    
    self.attachTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, PopViewHeight-10)];
    _attachTable.tag = 10002;
    _attachTable.backgroundColor = _attachTable.superview.backgroundColor;
    _attachTable.delegate = self;
    _attachTable.dataSource = self;
    [rightView addSubview:_attachTable];
    
    self.attachArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    if (IsiOS7Over) {
        UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
        [swipeGesture setDirection:UISwipeGestureRecognizerDirectionRight];
        [rightView addGestureRecognizer:swipeGesture];
    }
}

- (void)swipeGesture:(UIGestureRecognizer *)gesture {
    NSLog(@"SWIPE");
    if (gesture.state == UIGestureRecognizerStateRecognized) {
        NSLog(@"SWIPE RECOGNIZED");
        _contentView.scrollEnabled = YES;
        [_contentView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _attachArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"cellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    cell.backgroundColor = _attachTable.backgroundColor;
    
    NSDictionary *dic = [_attachArray objectAtIndex:indexPath.row];
    cell.textLabel.text = [dic objectForKey:@"title"];
    if (!IsiOS7Over) {
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.font = [UIFont systemFontOfSize:17.0];
        
        UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
        [swipeGesture setDirection:UISwipeGestureRecognizerDirectionRight];
        [cell addGestureRecognizer:swipeGesture];
    }
    
    AttachType attachType = [[dic objectForKey:@"type"] intValue];
    NSString *imageName;
    
    switch (attachType) {
        case FILE_TYPE:
            imageName = @"file_s";
            break;
        case PHOTO_TYPE:
            imageName = @"photo_s";
            break;
            
        case VIDEO_TYPE:
            imageName = @"videoBtn_s";
            break;
        default:
            break;
    }
    cell.imageView.image = [UIImage imageNamed:imageName];
    cell.imageView.contentMode = UIViewContentModeCenter;

    return cell;
}

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
    [_attachArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

//- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
//    [_attachArray exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
//}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"selected %d", indexPath.row);
}

- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
        return UITableViewCellEditingStyleDelete;
}

- (void)deleteBtnPressed:(UIButton *)deleteBtn {
    NSLog(@"deleteBtn:%d", deleteBtn.tag);
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x == 0) {
        _pageCtrl.currentPage = 0;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x >= 320.0) {
        scrollView.scrollEnabled = NO;
        _pageCtrl.currentPage = 1;
    } else {
        _pageCtrl.currentPage = 0;
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

}

#pragma mark - show and hide animations

- (void)showOrHidePopView {
    
    if (isMoving) {
        return;
    }
    
    _isShow = !_isShow;
    isMoving = YES;
    [UIView beginAnimations:@"move" context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animatedStop1:)];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    CGFloat top;
    
    if (_isShow) {
        top = ScreenHeight-PopViewHeight-SystemTakeHeight-UpMarginValue;
    } else {
        top = ScreenHeight-SystemTakeHeight;
    }
    self.top = top;
    [UIView commitAnimations];
}

- (void)animatedStop1:(id)sender {
    if (!_isShow) {
        isMoving = NO;
        return;
    }
    
    [UIView beginAnimations:@"move1" context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animatedStop2:)];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    CGFloat top = ScreenHeight-PopViewHeight-SystemTakeHeight+DownMarginValue;
    self.top = top;
    [UIView commitAnimations];
}

- (void)animatedStop2:(id)sender {

    [UIView beginAnimations:@"move2" context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animatedStop3:)];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    CGFloat top = ScreenHeight-PopViewHeight-SystemTakeHeight;
    self.top = top;
    [UIView commitAnimations];
}

- (void)animatedStop3:(id)sender {
    isMoving = NO;
}

@end
